package com.chenjt.springai.nine_rag.controller;

import com.chenjt.springai.nine_rag.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2025/5/28 9:09
 */
@RequiredArgsConstructor // 有参构造
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    /**
     * @RequiredArgsConstructor相当于以下构造方法
     */
    /*public ChatController(ChatClient chatClient){
        this.chatClient = chatClient;
    }*/

    /**
     * 阻塞调用
     * @param prompt 用户提示词
     * @return
     */
    @RequestMapping("/chat")
    public String chat(String prompt){
        return chatClient.prompt()
                .user(prompt)
                .call()// 阻塞调用
                .content();
    }


    /**
     * 流式调用
     * @param prompt
     * @return
     */
    @RequestMapping(value = "/streamChat", produces = "text/html;charset=utf-8")
    public Flux<String> streamChat(String prompt,String chatId){
        //1.保存会话id
        chatHistoryRepository.save("chat",chatId);
        //2.请求模型
        return chatClient.prompt()
                .user(prompt)
                // 将chatId访问，隔离所有的聊天窗口记忆
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()// 流式调用
                .content();
    }



}
